package interaction.input.concrete;

import processing.core.PGraphics;
import processing.core.PVector;
import interaction.ServiceLocator;
import interaction.input.DataComponent;
import interaction.sampling.Sample;
import interaction.sampling.SampleSet;
import interaction.sampling.matching.Matcher;

public class TestComponent extends DataComponent<Integer> {
	private Matcher signatureMatcher = ServiceLocator.getSampleMatcher();
	private SampleSet tapSignature;
	private SampleSet slapSignature;
	private Sample beat;
	private int taps = 0;
	private int slaps = 0;
	
	public TestComponent(PVector position, PVector size) {
		super(position, size);
	}

	protected void drawRelative(PGraphics g) {
		if (beat != null) {
			g.stroke(g.color(255));
			drawSpectrum(g, beat, new PVector());
		}
		
		boolean tapMatched = false;
		boolean slapMatched = false;
		
		if (beat != null) {
			System.out.println("got beat");
			
			double tapRating = signatureMatcher.match(beat, tapSignature);
			double slapRating = signatureMatcher.match(beat, slapSignature);
			double treshold = signatureMatcher.getAcceptanceTreshold();
			
			System.out.println(tapRating + " vs. " + slapRating);
			if ((tapRating >= treshold) && (tapRating > slapRating)) {
				System.out.println("Taps: " + ++taps);
				tapMatched = true;
			} else if ((slapRating >= treshold) && (slapRating > tapRating)) {
				System.out.println("Slaps: " + ++slaps);
				slapMatched = true;
			}
		}
		
		if (tapMatched) {
			g.stroke(g.color(255, 0, 0));
		} else {
			g.stroke(g.color(255));
		}
		drawSpectrum(g, tapSignature.getSampleAverage(), new PVector(0, g.height / 3));
		
		if (slapMatched) {
			g.stroke(g.color(255, 0, 0));
		} else {
			g.stroke(g.color(255));
		}
		drawSpectrum(g, slapSignature.getSampleAverage(), new PVector(0, g.height - (g.height / 3)));
		
		beat = null;
	}
	
	public void drawSpectrum(PGraphics g, Sample s, PVector pos)
	{
		g.pushMatrix();
		g.translate(pos.x, pos.y + 40);
		int i = 0;
		for (Float f : s) {
			g.line(i, 0, i, f * 4);
			i++;
		}
		g.popMatrix();
	}
	
	public void setSlapSignature(SampleSet slapSignature) {
		this.slapSignature = slapSignature;
	}
	
	public void setTapSignature(SampleSet tapSignature) {
		this.tapSignature = tapSignature;
	}
	
	public void beatReceived(Sample s) {
		this.beat = s;
	}

}
